/**
 * COPYRIGHT HangZhou 99Cloud Technology Company Limited
 * All right reserved.
 */
package com.zfsmart.projectdemo.asset.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zfsmart.component.common.bean.restful.entity.ServiceException;
import com.zfsmart.component.feign.basefeign.AccountFeignUtil;
import com.zfsmart.component.feign.basefeign.OrderFeignUtil;
import com.zfsmart.projectdemo.asset.entity.User;
import com.zfsmart.projectdemo.asset.mapper.UserMapper;
import com.zfsmart.projectdemo.asset.service.UserService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description
 * @Author 薛铁琪
 * @CreateTime 2021/8/2 11:16
 * @Version 1.0
 */
@Service
@Slf4j
public class Test {

    @Autowired
    UserService userService;
    @Autowired
    OrderFeignUtil orderFeignUtil;
    @Autowired
    AccountFeignUtil accountFeignUtil;
    @Autowired
    UserMapper userMapper;

    // 限流与阻塞处理
//    @SentinelResource(value = "doSomeThing", blockHandler = "exceptionHandler")
    @SentinelResource(value = "doSomeThing")
    public void doSomeThing(String str) {
        log.info(str);
    }

    public void exceptionHandler(String str, BlockException ex) {
        log.error("流控策略生效 捕获异常", ex);
        throw new ServiceException("流控策略生效");
    }


    // 熔断与降级处理
    @SentinelResource(value = "doSomeThing2", fallback = "fallbackHandler")
//    @SentinelResource(value = "doSomeThing2")
    @Transactional
    public void doSomeThing2(String str) {
        log.info(str);
        userMapper.insert(User.builder().email("1").age(1).name("1").build());
        throw new ServiceException("发生异常");
    }

    public void fallbackHandler(String str) {
        log.error("降级熔断生效 捕获异常");
        //throw new ServiceException("降级熔断生效");
    }


    @GlobalTransactional
//    @Transactional
    public void doSomeThing3() {
        log.info(RootContext.getXID());
        userMapper.insert(User.builder().email("1").age(1).name("1").build());
        orderFeignUtil.test();
        accountFeignUtil.test();
//        throw new ServiceException("测试全局事务");
    }

    @Transactional
    public void doSomeThing4() {
        userMapper.insert(User.builder().email("1").age(1).name("1").build());
        throw new ServiceException("测试本地事务");
    }
}
